let conn = require('./connection.js')
let uuid = require('node-uuid')

const tokenExpireTime = 7200

module.exports = {
  setToken: function (user) {
    return new Promise((resolve, reject) => {
      if (user === null) {
        return resolve({ success: false, msg: 'null user' })
      }
      let accessToken = uuid.v1()
      let refreshToken = uuid.v1()
      let createTime = new Date().getTime()
      let k = 'Session:' + accessToken
      user.refreshToken = refreshToken
      conn.setCache(k, JSON.stringify(user), tokenExpireTime).then(result => {
        if (result.success) {
          resolve({ success: true, accessToken, createTime, expireTime: tokenExpireTime, refreshToken })
        } else {
          resolve(result)
        }
      })
    })
  },
  checkToken: function (accessToken) {
    return new Promise((resolve, reject) => {
      let k = 'Session:' + accessToken
      conn.existCache(k).then(result => {
        resolve(result)
      })
    })
  },
  getToken: function (accessToken) {
    return new Promise((resolve, reject) => {
      let k = 'Session:' + accessToken
      conn.getCache(k).then(result => {
        if (result.success) {
          resolve({ success: true, user: result.data })
        } else {
          resolve(result)
        }
      })
    })
  },
  refreshToken: function (accessToken, refreshToken) {
    let $this = this
    console.log('token refreshed')
    return new Promise((resolve, reject) => {
      $this.getToken(accessToken).then(result => {
        if (result.success) {
          if (result.user.refreshToken !== refreshToken) {
            return resolve({ success: false, msg: '错误的刷新令牌' })
          }
          $this.setToken(result.user).then(resultSetToken => {
            if (resultSetToken.success) {
              $this.removeToken(accessToken)
            }
            resolve(resultSetToken)
          })
        } else {
          resolve(result)
        }
      })
    })
  },
  removeToken: function (accessToken) {
    return new Promise((resolve, reject) => {
      let k = 'Session:' + accessToken
      conn.removeCache(k).then(result => {
        resolve(result)
      })
    })
  }
}
